import RecruitAPI from '../../common/api/lookrecruit/recruit.api.js';
import { DictionaryType, requestDict } from "../../common/dictionary/dictionary-type.js";


(function (window, document, $) {
  let _vm, thisindex, creatorArr = [], userInfo;
  let flag = true; //flag 节流阀
  let _json = Utils.ParsingUrl(window.location);
  $(function () {
    _vm = new Vue({
      el: "#recruitdetails",
      data() {
        return {
          entries: {
            "cvSnapshot": {
              "educationExps": [],
              "internExps": [],
              "workExps": [],
              "skillCerts": []
            }
          },
          statusdata: [],
          statusInfo: {},
          totaljobdata: [],
          stadata: ""
        }
      },
    });
    $('body').attr('data-weui-theme', 'light'); //强制光明模式
    _initOperate()
    _initBtn()
    _initCommand()
    _initScroll()
  });
  // 初始化操作
  const _initCommand = async (jobcvid) => {
    userInfo = await RecruitAPI.getLoginUserToStaff()
    let aslistdata = {
      "emplId": userInfo.id,
      "jobCVIds": "",
      "searchInfo": "",
    }
    let recArr = _json.id.split(',')
    if (!Utils.IsNotNull(_json.entertype)) {
      let thisAslist = {
        "emplId": userInfo.id,
        "jobCVIds": [...recArr],
        "searchInfo": "",
      }
      RecruitAPI.jobAslist(thisAslist).then(res => {
        let thisjobdata
        if (Utils.IsNotNull(jobcvid)) {
          let thisjobArr = res.items.filter(item => {
            return item.id == jobcvid
          })
          thisjobdata = thisjobArr[0]
        }
        else {
          thisjobdata = res.items[0]
        }
        let jobid = res.items.map(item => item.id)
        _vm.totaljobdata = [...res.items]
        if (Utils.IsNotNull(thisjobdata)) {
          processingData(thisjobdata, jobid, res.items)
        }
        else {
          $.toptip('该简历推送已被撤回，暂无法查看', 'warning');
          $('.rcnopass').each((index, item) => {
            $(item).addClass('asdisable')
          })
        }
      })
    }
    else {
      let thisAslist = {
        "emplId": userInfo.id,
        "jobCVIds": Utils.IsNotNull(jobcvid) ? [jobcvid] : [_json.id],
        "searchInfo": "",
      }
      // 查看总的有几条
      RecruitAPI.jobAslist(aslistdata).then(res => {
        let totalaslist = {
          "emplId": userInfo.id,
          "jobCVIds": "",
          "searchInfo": "",
          "pageIndex": 0,
          "pageSize": res.totalCount
        }
        // 获取总的条数
        RecruitAPI.jobAslist(totalaslist).then(res => {
          let jobdata = { ...res }
          _vm.totaljobdata = [...jobdata.items]
          let jobid = jobdata.items.map(item => item.id)
          // 获取当前这条
          RecruitAPI.jobAslist(thisAslist).then(res => {
            let thisjobdata = res.items[0]
            if (Utils.IsNotNull(thisjobdata)) {
              processingData(thisjobdata, jobid, jobdata)
            }
            else {
              $.toptip('该简历推送已被撤回，暂无法查看', 'warning');
            }
          })
        })
      })
    }


  }
  // 处理数据
  const processingData = (thisjobdata, jobid, jobdata) => {
    let thisarrindex = jobid.indexOf(thisjobdata.id)
    thisindex = thisarrindex + 1
    // 有评估信息
    if (Utils.IsNotNull(thisjobdata.assessRecords)) {
      let curUserId = JSON.parse(Utils.GetSessionStorage('SNLoginUserInfo')).curUserId
      // 判断评估消息是否有自己的
      creatorArr = []
      creatorArr = thisjobdata.assessRecords.filter(item => {
        return item.creatorId == curUserId
      })
      //是自己的评估消息
      if (Utils.IsNotNull(creatorArr)) {
        let statusdataArr = [..._vm.statusdata]
        let statusInfo = statusdataArr.filter(item => {
          return item.value == creatorArr[0].status
        })
        // 评估信息中的状态 数据字典中 存在
        if (Utils.IsNotNull(statusInfo)) {
          $('#restatus').css('display', 'block')
          statusInfo[0].displayName == "合格" ? $('#pdstatus').removeClass('unfile').removeClass('pending').addClass('hg')
            : statusInfo[0].displayName == "不合格" ? $('#pdstatus').removeClass('hg').removeClass('pending').addClass('unfile')
              : statusInfo[0].displayName == "待定" ? $('#pdstatus').removeClass('unfile').removeClass('hg').addClass('pending') : ""
          _vm.statusInfo = {
            ...statusInfo[0]
          }
          statusdataArr.forEach(item => {
            item.displayName == statusInfo[0].displayName ? item.selectst = true : item.selectst = false
          })
        }
        // 不存在
        else {
          $('#restatus').css('display', 'none')
          _vm.statusdata.forEach(item => {
            item.selectst = false
          })
        }
      }
      else {
        $('#restatus').css('display', 'none')
        _vm.statusdata.forEach(item => {
          item.selectst = false
        })
      }
    }
    // 没有评估信息
    else {
      creatorArr = []
      $('#restatus').css('display', 'none')
      _vm.statusdata.forEach(item => {
        item.selectst = false
      })
    }
    let max = 0
    let minwork = new Date().getTime()
    let eduredegree, rcworkExps
    // 教育经历
    let edudegree = [...thisjobdata.cvSnapshot.educationExps]
    for (let i = 0; i < edudegree.length; i++) {
      if (new Date(edudegree[i].endDate) > max) {
        max = new Date(edudegree[i].endDate).getTime()
        eduredegree = edudegree[i]
      }
    }
    // 工作经历
    let recriutworkExps = [...thisjobdata.cvSnapshot.workExps]
    let sjworkExps = "无工作经验"
    let addSum = 0
    if (Utils.IsNotNull(recriutworkExps)) {
      for (let i = 0; i < recriutworkExps.length; i++) {
        // if (new Date(recriutworkExps[i].startDate).getTime() < minwork) {
        //   minwork = new Date(recriutworkExps[i].startDate).getTime()
        //   rcworkExps = recriutworkExps[i]
        // }
        let addDifference = ((new Date(recriutworkExps[i].endDate).getTime() - new Date(recriutworkExps[i].startDate).getTime()) / 31536000000)
        addSum = Number(addSum) + Number(addDifference)
      }
      addSum = addSum.toFixed(1)
      if (addSum < 1) {
        sjworkExps = "1年以下工作经验"
      }
      else {
        sjworkExps = `${addSum}年工作经验`
      }
      // sjworkExps = ((new Date().getTime() - new Date(rcworkExps.startDate).getTime()) / 31536000000).toFixed(1)
      // if (sjworkExps < 1) {
      //   sjworkExps = "1年以下工作经验"
      // }
      // else {
      //   sjworkExps = `${sjworkExps}年工作经验`
      // }
    }
    // 基本信息
    let recruitData = {
      "id": thisjobdata.id,
      "rename": thisjobdata.cvSnapshot.name,
      "regender": thisjobdata.cvSnapshot.gender == 1 ? " / 先生" : " / 女士",
      "rejobPostName": thisjobdata.jobPostName,
      "reage": Utils.IsNotNull(thisjobdata.cvSnapshot.age) ? thisjobdata.cvSnapshot.age + '岁 |' : "",
      "reworkExps": sjworkExps + ' |',
      "redegree": eduredegree.degree,
      "reprofession": Utils.IsNotNull(eduredegree.profession) ? ' | ' + eduredegree.profession : ""
    }
    // 求职意向
    let intention = {
      "cvExceptedSalary": thisjobdata.cvExceptedSalary,
      "cvCareerObjective": thisjobdata.cvCareerObjective,
      "intentionCity": thisjobdata.cvSnapshot.intentionCity
    }

    let detailsdata = {
      "totalCount": `共${Utils.IsNotNull(jobdata.totalCount) ? jobdata.totalCount : jobdata.length}份`,
      "thisCount": `第${thisindex}份/`,
      "cvSnapshot": thisjobdata.cvSnapshot,
      ...recruitData,
      ...intention,
    }
    _vm.entries = { ...detailsdata }
    flag = true;
  }
  const _initOperate = () => {
    requestDict(DictionaryType.DELIERY_TYPE).then(res => {
      res.data.unshift(res.data[res.data.length - 1])
      res.data.pop()
      res.data.forEach(item => {
        item.displayName == "合格" ? item.stadata = 'hgst' : item.displayName == "不合格" ? item.stadata = 'unqualifiedst' : item.displayName == "待定" ? item.stadata = 'pendingst' : ""
      })
      _vm.statusdata = [...res.data]
    })

    $(document).on('click', '.rcnopass:not(.asdisable)', function () {
      let datastatus = $(this).attr('data-status')
      let editAssess = {
        "status": datastatus,
        "remark": "",
        "emplInfo": {
          "id": userInfo.id,
          "name": userInfo.name,
          "numCode": userInfo.code
        }
      }
      if (Utils.IsNotNull(creatorArr)) {
        RecruitAPI.editAssess(creatorArr[0].jobCVId, creatorArr[0].seq, editAssess).then(res => {
          $.toptip('请求成功。', 'success');
          _initCommand(_vm.totaljobdata[thisindex - 1].id)
        })
      }
      else {
        RecruitAPI.jobAssess({ ...editAssess, "jobCVId": _vm.entries.id }).then(res => {
          $.toptip('请求成功。', 'success');
          _initCommand(_vm.totaljobdata[thisindex - 1].id)
        })
      }
    })
  }
  // 初始化上下页键
  const _initBtn = () => {
    $('#rightBtn').on('click', function () {
      if (flag) {
        flag = false; // 关闭节流阀 
        if (thisindex == _vm.totaljobdata.length) {
          thisindex = 0
        }
        let jobid = _vm.totaljobdata.map(item => item.id)
        if (Utils.IsNotNull(_vm.totaljobdata[thisindex])) {
          processingData(_vm.totaljobdata[thisindex], jobid, _vm.totaljobdata)
        }
      }
    });
    // 点击左侧按钮
    $('#leftBtn').on('click', function () {
      if (flag) {
        flag = false;
        thisindex = thisindex - 1
        if (thisindex == 0) {
          thisindex = _vm.totaljobdata.length
        }
        let jobid = _vm.totaljobdata.map(item => item.id)
        if (Utils.IsNotNull(_vm.totaljobdata[thisindex - 1])) {
          processingData(_vm.totaljobdata[thisindex - 1], jobid, _vm.totaljobdata)
        }
      }
    });
  }
  // 左右滑动
  const _initScroll = () => {
    let startX, startY, EndX, EndY, X, Y
    $("body").on("touchstart", function (e) {
      e.preventDefault();
      startX = e.originalEvent.changedTouches[0].pageX;
      startY = e.originalEvent.changedTouches[0].pageY;
      flag = true
    });
    $("body").on("touchmove", function (e) {
      e.preventDefault();
      EndX = e.originalEvent.changedTouches[0].pageX;
      EndY = e.originalEvent.changedTouches[0].pageY;
      X = EndX - startX;
      Y = EndY - startY;
      // 左滑
      if (Math.abs(X) > Math.abs(Y) && X > 0) {
        $('#leftBtn').click()
        flag = false
      } else if (Math.abs(X) > Math.abs(Y) && X < 0) {
        $('#rightBtn').click()
        flag = false
      }
    });
  }
})(window, document, jQuery)

